using System;
using System.Collections.Generic;

using Gtk;

namespace repragator
{
	public class MacroNode : Gtk.TreeNode
	{
		[Gtk.TreeNodeValue(Column = 0)]
		public string Name
		{
			get;
			set;
		}
		
		public MacroNode(string name)
		{
			this.Name = name;	
		}
	}
	
	public partial class MacroEditor : Gtk.Dialog
	{
		public Dictionary<string, Macro> Macros
		{
			get
			{
				return this.macros;	
			}
			set
			{
				this.macros = value;
			
				this.LoadMacros();
			}
		}
		
		private Dictionary<string, Macro> macros;
		
		public MacroEditor ()
		{
			this.Build ();
			
			this.macroNodeView.AppendColumn("Name", new Gtk.CellRendererText(), "text", 0);
			
			this.macroNodeView.NodeStore = new Gtk.NodeStore(typeof(MacroNode));
			
			this.macroNodeView.NodeSelection.Changed += new EventHandler(this.OnSelectionChanged);
		}
		
		private void LoadMacros()
		{
			foreach (KeyValuePair<string, Macro> item in this.macros)
			{
				this.macroNodeView.NodeStore.AddNode(new MacroNode(item.Key));
			}
		}

		protected void OnAddButtonClicked (object sender, System.EventArgs e)
		{
			if (this.macroNameEntry.Text == string.Empty)
			{
				MessageDialog message = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, false, "Enter a name for your macro.");
				
				message.Run();
				
				message.Destroy();
				
				return;
			}
			
			this.macros.Add(this.macroNameEntry.Text, new Macro(this.macroNameEntry.Text, this.macroTextView.Buffer.Text));
			
			this.macroNodeView.NodeStore.AddNode(new MacroNode(this.macroNameEntry.Text));
		}

		protected void OnRemoveButtonClicked (object sender, System.EventArgs e)
		{
			NodeSelection selection = this.macroNodeView.NodeSelection;
			
			MacroNode node = (MacroNode)selection.SelectedNode;
			
			if (node == null)
				return;
			
			this.macros.Remove(node.Name);
			
			this.macroNodeView.NodeStore.RemoveNode(node);
		}
		
		protected void OnSelectionChanged(object sender, EventArgs e)
		{
			NodeSelection selection = (NodeSelection)sender;
			
			MacroNode node = (MacroNode)selection.SelectedNode;
		
			if (node == null)
				return;
			
			if (this.macroNameEntry.Text != node.Name && this.macroNameEntry.Text != string.Empty && this.macros.ContainsKey(this.macroNameEntry.Text))
			{
				this.macros[this.macroNameEntry.Text].Text = this.macroTextView.Buffer.Text;
			}
			
			this.macroNameEntry.Text = node.Name;
				
			this.macroTextView.Buffer.Text = this.macros[node.Name].Text;
		}
	}
}

